<template>
  <div class="seach_container">
    <div class="searchbox_content">
      <input
        type="text"
        v-model="iptValue"
        placeholder="要素编码查询"
        @keyup.enter="handleEnter"
      />
      <div title="清空" class="input_clear" @click="handleClear"></div>
      <button class="seach_button" @click="handleEnter"></button>
    </div>
  </div>
  <div class="seach_info" v-show="isShow" @click="FlytoLine">
    <ol>
      <li class="li">{{ pipeRemark }}</li>
      <div>来源:管网检测</div>
    </ol>
  </div>
  <!-- v-show="showBaidu" -->
  <div v-show="showBaidu" class="baidu_box">
    <div class="seach_info_a">
      <div class="info_a" v-for="item in arrBD" @click="Flyto(item.co)">
        <div class="li">{{ item.index }}{{ item.name }}</div>
        <div>来源:网络定位</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, toRaw } from 'vue'
import emitter from '@/utils/bus'
import View from 'ol/View.js'
import Overlay from 'ol/Overlay' // 引入覆盖物模块
import VectorLayer from 'ol/layer/Vector.js'
import VectorSource from 'ol/source/Vector.js'
import Feature from 'ol/Feature.js'
import Point from 'ol/geom/Point.js'
import LineString from 'ol/geom/LineString.js'
import Polygon from 'ol/geom/Polygon.js'
import * as turf from '@turf/turf' //引入turf做buffer缓冲区分析
import { Stroke, Style, Circle, Fill } from 'ol/style'
import olstyleStroke from 'ol/style/Stroke'
import olstyleFill from 'ol/style/Fill'
import olStyle from 'ol/style/Style'
import Text from 'ol/style/Text.js'
import Icon from 'ol/style/Icon.js'
import { transform } from 'ol/proj'
import { composeCssTransform } from 'ol/transform'
import { getPipeInfo, getPipePointInfo, getBaiduApi } from '@/api/index'
import { userMap, userSource } from '@/store/index'
import { require } from '@/utils/require'
import axios from 'axios'
import { myProjection, params } from '@/views/map/mapHooks/ArcGisMap'
import baidu from '../api/baidu'

let map = userMap() //接收
let source = userSource()
let list
// 单线起点
let PXsource
let PXLayer
let PXFeature
// 单线终点
let PYsource
let PYLayer
let PYFeature
// 单线
let PLinesource
let PLineLayer
let PLineFeature
// 百度地图飞行图层-点
let BDLayer
let BDSource
let BDFeature
const isShow = ref(false)
const showBaidu = ref(false)
const iptValue = ref('')
const pipeRemark = ref('')
const startId = ref('')
const endId = ref('')
const arrBD = ref([])
onMounted(() => {
  list = toRaw(map.map)
  // console.log('传过来的地图容器', list)
  // 线要素的起点图层
  PXsource = new VectorSource({
    wrapX: false,
  })
  PXLayer = new VectorLayer({
    source: PXsource,
    zIndex: 999,
    style: new Style({
      image: new Circle({
        radius: 5,
        fill: new Fill({
          color: [255, 165, 0, 1],
        }),
        stroke: new Stroke({
          color: [0, 255, 0, 1],
          width: 2.5,
        }),
      }),
      text: new Text({
        font: '15px A_QiChengINFO',
        text: '\u0028',
        scale: 2,
        fill: new Fill({
          color: 'rgba(255,165,0,1)',
        }),
      }),
    }),
  })
  list.addLayer(PXLayer)
  // 线要素的终点图层
  PYsource = new VectorSource({
    wrapX: false,
  })
  PYLayer = new VectorLayer({
    source: PYsource,
    zIndex: 999,
    style: new Style({
      image: new Circle({
        radius: 5,
        fill: new Fill({
          color: [0, 255, 0, 1],
        }),
        stroke: new Stroke({
          color: [255, 165, 0, 1],
          width: 2.5,
        }),
      }),
      text: new Text({
        font: '15px A_QiChengINFO  ',
        text: '\u0029',
        scale: 2,
        fill: new Fill({
          color: 'rgba(255,165,0,1)',
        }),
      }),
    }),
  })
  list.addLayer(PYLayer)
  // 线要素缓冲区图层(单线)
  PLinesource = new VectorSource({
    wrapX: false,
  })
  PLineLayer = new VectorLayer({
    title: 'PLineLayer',
    source: PLinesource,
    zIndex: 99,
  })
  // 百度飞行
  // 空间查询图层--飞行--单点
  BDSource = new VectorSource({
    wrapX: false,
  })
  BDLayer = new VectorLayer({
    source: BDSource,
    zIndex: 9999,
  })
  list.addLayer(BDLayer)
  /* 分割线 */
})
const strVal = ref('')
// 搜索探测
const handleEnter = () => {
  // console.log(iptValue.value.indexOf('-'))
  if (iptValue.value.indexOf('-') == -1) {
    baidu.jsonp({
      url: 'https://api.map.baidu.com/place/v2/search',
      //
      data: {
        query: `${iptValue.value}`,
        region: '昆山市',
        output: 'json',
        ak: 'DRA495273DCI0i5g6KxrEP9eM2NeolIt',
      },
      callback: function (res) {
        console.log('333', res)
        const arr = res.results
        const arr_ = []
        // console.log(transform([114.3, 114.2], 'EPSG:4326', 'EPSG:KSZB'))
        for (let i = 0; i < arr.length; i++) {
          const co_ = [arr[i].location.lng, arr[i].location.lat]

          const obj = {
            index: i + 1 + '.',
            name: arr[i].name,
            co: co_,
          }
          arr_.push(obj)
        }
        arrBD.value = arr_
        // console.log('BD数组', toRaw(arrBD.value))
        showBaidu.value = true
        isShow.value = false
      },
    })
    /* 分割线 */
  } else {
    showBaidu.value = false
    var str_1 = iptValue.value.replace(/\s*/g, '') //去掉所有空格
    strVal.value = str_1
    getPipeInfo(str_1).then((res) => {
      console.log(res)
      if (res.data.length >= 1) {
        const list = res.data[0]
        pipeRemark.value = str_1
        startId.value = list.startId
        endId.value = list.endId
        console.log(startId.value, endId.value)
        getPipePointInfo(startId.value).then((res) => {
          startX.value = res.data[0].x
          startY.value = res.data[0].y
          console.log('起点', startX.value, startY.value)
          // 加载起点要素
          PXFeature = new Feature({
            geometry: new Point([startX.value, startY.value]),
          })
          if (PXFeature.getGeometry() != null) {
            PXsource.clear()
          }
          //  PXsource.addFeature(PXFeature)
        })
        isShow.value = true
      } else {
        isShow.value = false
      }
    })
  }
}
const test = () => {
  baidu.jsonp({
    url: 'https://api.map.baidu.com/place/v2/search',
    //
    data: {
      query: '市政府',
      region: '昆山市',
      output: 'json',
      ak: 'DRA495273DCI0i5g6KxrEP9eM2NeolIt',
    },
    callback: function (ret) {
      console.log('333', ret)
    },
  })
}

// 清空
const handleClear = () => {
  iptValue.value = ''
  isShow.value = false
  showBaidu.value = false
}
const startX = ref()
const startY = ref()
const endX = ref()
const endY = ref()
// 管网查询
const FlytoLine = () => {
  getPipePointInfo(endId.value).then((res) => {
    console.log(res)
    endX.value = res.data[0].x
    endY.value = res.data[0].y
    console.log('终点', endX.value, endY.value)
    // // 加载终点要素
    PYFeature = new Feature({
      geometry: new Point([endX.value, endY.value]),
    })
    if (PYFeature.getGeometry() != null) {
      PYsource.clear()
    }
    // PYsource.addFeature(PYFeature)
    // // 加载缓冲区--只有4326可以使用turf
    const arrKSZB = [
      [startX.value, startY.value],
      [endX.value, endY.value],
    ]
    // console.log('缓冲区', arrKSZB)
    let arr4326 = arrKSZB.map((item) => {
      return transform(item, 'EPSG:KSZB', 'EPSG:4326')
    })
    const lineString = turf.lineString(arr4326)
    // 0.1米=0.00006214 英里
    // 0.5米=0.0003107 英里
    const buffer = turf.buffer(lineString, 0.0003107, { units: 'miles' })
    let buffered = buffer.geometry.coordinates[0]
    let testarr = buffered.map((item) => {
      return transform(item, 'EPSG:4326', 'EPSG:KSZB')
    })
    console.log(testarr)
    // PLineFeature = new Feature({
    //   type: 'Polygon',
    //   geometry: new Polygon([testarr]),
    // })
    // if (PLineFeature.getGeometry() != null) {
    //   PLinesource.clear()
    // }
    PLineFeature = new Feature({
      geometry: new LineString([
        [startX.value, startY.value],
        [endX.value, endY.value],
      ]),
      attributes: [startId.value, endId.value],
      attributes2: strVal.value,
      layerName: 'detectLayer',
    })
    list.addLayer(PLineLayer) //在这里添加图层使交互可以捕捉到
    PLinesource.addFeature(PLineFeature)
    PLineFeature.setStyle(function (resolution) {
      //监听分辨率跟随地图缩放
      return [
        new olStyle({
          fill: new olstyleFill({
            color: '#ff0000',
          }),
          stroke: new olstyleStroke({
            color: '#ff0000',
            width: 4,
          }),
        }),
      ]
    })
    source.PLinesource = PLinesource //存入菠萝
    const lineS = toRaw(source.PLinesource)
    console.log('缓冲区', lineS)
    list.getView().animate({
      center: [endX.value, endY.value],
      zoom: 9,
    })
  })
}
// 网络地图查询
const Flyto = (val) => {
  const co = transform(toRaw(val), 'EPSG:4326', 'EPSG:KSZB')
  console.log('网络查询', co)
  BDFeature = new Feature({
    geometry: new Point(co),
  })
  BDSource.addFeature(BDFeature)
  BDFeature.setStyle(function (resolution) {
    //监听分辨率跟随地图缩放
    return [
      new Style({
        image: new Icon({
          anchor: [0.5, 1.2], //锚点
          opacity: 1,
          scale: list.getView().getZoom() / 22,
          // src: require('@/assets/images/mark.png'),
          src: require('/vue3Ol/images/mark.png'),
        }),
      }),
    ]
  })

  list.getView().setZoom(9)
  list.getView().setCenter(co)
}
</script>
<style lang="less" scoped>
.seach_container {
  position: absolute;
  z-index: 2;
  pointer-events: auto;
  width: 370px;
  box-sizing: border-box;
  box-shadow: 1px 2px 1px rgb(0 0 0 / 15%);
  .searchbox_content {
    background-color: #0a163cc9;
    border: 1px solid #80eeff;
    display: flex;
    input {
      color: #80eeff;
      width: 327px;
      display: block;
      background: transparent;
      outline: none;
      border: none;
      &:focus {
        border: none;
      }
    }
    .input_clear {
      width: 37px;
      display: block;
      background: url('@/assets/images/qk.png') 10px 5px / 26px 26px no-repeat;
      right: 40px;
      cursor: pointer;
    }
    .seach_button {
      outline: none;
      border: none;
      cursor: pointer;
      height: 36px;
      display: block;
      background: url('@/assets/images/ss.png') 0px 0px / 100% 100% no-repeat;
      width: 36px;
      &:focus {
        border: none;
      }
    }
  }
}
.baidu_box {
  :deep(.seach_info_a) {
    scrollbar-color: #5385b1 #0a163cc9; /* 第一个方块颜色，第二个轨道颜色(用于更改火狐浏览器样式) */
    scrollbar-width: thin; /* 火狐滚动条无法自定义宽度，只能通过此属性使滚动条宽度变细 */
    -ms-overflow-style: none; /* 隐藏滚动条（在IE和Edge两个浏览器中很难更改样式，固采取隐藏方式） */
  }
  :deep(.seach_info_a::-webkit-scrollbar) {
    width: 5px;
    height: 4px; // 纵向滚动条 必写
  }
  // 解决XY滚动条右下角白框
  :deep(.seach_info_a::-webkit-scrollbar-corner) {
    background: rgba(0, 0, 0, 0);
  }
  :deep(.seach_info_a::-webkit-scrollbar-thumb) {
    background-color: #5385b1;
    border-radius: 5px;
  }
}
.seach_info {
  z-index: 100;
  max-height: 415px;
  background-color: #0a163cc9;
  border: 2px solid #80eeff;
  color: #80eeff;
  position: absolute;
  top: 42px;
  width: 370px;
}
.seach_info_a {
  z-index: 100;
  max-height: 415px;
  background-color: #0a163cc9;
  border: 2px solid #80eeff;
  color: #80eeff;
  position: absolute;
  top: 42px;
  width: 370px;
  overflow: auto;
}
.info_a {
  padding-left: 30px;
}
.info_a:hover {
  background-color: #070f29c9;
}
.popup {
  width: 300px;
  height: 100px;
  background: #fff;
  position: absolute;
  top: -115px;
  left: -150px;
  box-sizing: border-box;
  padding: 10px;
  z-index: 999999;

  &::after {
    content: '';
    display: block;
    position: absolute;
    width: 20px;
    height: 20px;
    background: #fff;
    bottom: -10px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
  }

  .icon-close {
    position: absolute;
    top: 0px;
    right: 8px;
    cursor: pointer;
  }

  .content {
    margin-top: 13px;
  }
}
.li {
  color: #cfe818;
}
</style>
